# coding=utf-8

import sys
import time
import datetime

from builtins import int

sys.path.append("..")
from common.mysql.connect import MysqlConnector
from common.redis.connect import RedisConnector
from common.utils.time import get_yesterday_date
from common.utils.time import turn_date_to_ts
from logic.goods_cate_logic import GoodsCateroryLogic


def goods_cate_sale_info(mysql, category_id, date):
    """ 商品分类每天销售信息汇总
    """
    # 根据时间戳获取当天的开始和结束时间戳，作为基准
    ts_start = turn_date_to_ts(date)
    ts_end = ts_start + 60 * 60 * 24 - 1

    goods_cate_logic = GoodsCateroryLogic()

    goods_sale_res = goods_cate_logic.get_goods_cate_everyday_sale_info(mysql, category_id, ts_start, ts_end)
    inlay_goods_sale_res = goods_cate_logic.get_goods_cate_inlay_everyday_sale_info(mysql, category_id, ts_start, ts_end)
    goods_sale_res.extend(inlay_goods_sale_res)

    # 获取写数据的数据库连接实例
    mysql_db_data = MysqlConnector("data")

    sql_insert = "insert into goods_category (`goods_category_id`, `date`, `order_num`, `order_amount`,\
         `refund_order_num`, `refund_order_amount`) values "

    # cur_date = turn_ts_to_date(ts_start) + '.000'
    if not goods_sale_res:
        # 当天没有售出，td中写入一条空值
        # sql_insert += " (%d, %d, %d, %f, %d, %f) " % (category_id, ts_start, 0, 0.00, 0, 0.00)
        return True
    else:
        # 当天有售出，汇总售出结果，并写入td
        sale_num_amount = cal_sale_num_amount(goods_sale_res)
        sql_insert += " (%d, %d, %d, %f, %d, %f) " % \
        (category_id, ts_start, sale_num_amount['order_num'], sale_num_amount['order_amount'],
         sale_num_amount['refund_order_num'], sale_num_amount['refund_order_amount'])

    exec_res = mysql_db_data.execute(sql_insert)
    if not exec_res:
        return False
    return True


if __name__ == '__main__':
    """ 商品分类相关数据处理
    """
    # 获取要处理的日期
    if len(sys.argv) == 2:
        # 外部传递进来
        date = sys.argv[1]
    else :
        # 默认取前一天的日期
        date = datetime.datetime.strftime(get_yesterday_date(), "%Y-%m-%d")

    redis_14 = RedisConnector(14)
    mysql_db_order = MysqlConnector("order")

    while True:
        time.sleep(0.1)
        goods_cate_id_pop = redis_14.rpop('goods_category_id_list')
        # 取出之后立马放回去
        redis_14.lpush('goods_category_id_list', goods_cate_id_pop)

        if goods_cate_id_pop and (not redis_14.sismember('goods_cate_list_' + date, goods_cate_id_pop)):
            res = goods_cate_sale_info(mysql_db_order, int(goods_cate_id_pop), date)
            if res:
                redis_14.sadd('goods_cate_list_' + date, goods_cate_id_pop)
        else :
            print(date + " no more data")
            break
